package com.ychs.lawyerback.service.impl;

import com.ychs.lawyerback.common.ResultCode;
import com.ychs.lawyerback.dto.DocumentQueryDTO;
import com.ychs.lawyerback.exception.BussinessException;
import com.ychs.lawyerback.mapper.DocumentMapper;
import com.ychs.lawyerback.pojo.DocumentEntity;
import com.ychs.lawyerback.service.DocumentService;
import com.ychs.lawyerback.vo.DocumentQueryVO;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * @author qiumengyao
 * @version 1.0
 * @date 2025/8/15
 */

@Service
public class DocumentServiceImpl implements DocumentService {

    @Autowired
    private DocumentMapper documentMapper;

    @Value("${file.upload-dir}")
    private String uploadDir; //丛培配置文件获取上传目录

    // 初始化方法：项目启动时执行，确保目录存在
    @PostConstruct
    public void initUploadDir() {
        // 手动创建目录（支持多级目录）
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            boolean isCreated = dir.mkdirs();

            if (isCreated) {
                System.out.println("上传目录创建成功：" + uploadDir);
            } else {
                System.err.println("警告：上传目录创建失败，请检查权限！路径：" + uploadDir);
            }
        } else {
            System.out.println("上传目录已存在：" + uploadDir);
        }
    }

    /**
     * 文件上传
     * @param
     * @param files
     * @param fileType
     */
    @Override
    public void uploadDocument( MultipartFile[] files, Integer fileType,String uploadName) throws IOException {

        // 判断文件是否为空
        if (files == null || files.length == 0) {
            return;
        }


        for (MultipartFile file : files) {
            // 1. 生成唯一文件名
            String originalName = file.getOriginalFilename();

            String suffix = originalName.substring(originalName.lastIndexOf("."));//提取文件后缀如（.pdf)
            String uuidFileName = UUID.randomUUID().toString().replace("-", "") + suffix; //生成UUID文件名

            //保存文件到本地目录
            //
            String filePath = uploadDir + File.separator + uuidFileName;  //目录加文件名
//            String relativePath = "/uploads/" + fileName; // 前端可访问的路径

            // 2. 保存文件到本地目录
            file.transferTo(new File(filePath));

            // 3. 保存记录到数据库
            DocumentEntity record = new DocumentEntity();
//            record.setTempId(tempId);         // 关联同一批次
            record.setFileName(uuidFileName);
//            record.setFileName(originalName); // 原始文件名
            record.setFilePath(filePath);     // 本地存储路径
//            record.setFilePath(relativePath);
            record.setFileType(fileType);     // 文件类型
            record.setStatus(0);              // 初始状态：未审阅
            record.setUploadTime(new Date());
            record.setUploadName(uploadName);
            documentMapper.insert(record);
        }
    }


    /**
     * 文件查找
     * @param documentQueryDTO
     * @return
     */
    @Override
    public Object getDocumentList(DocumentQueryDTO documentQueryDTO) {
        List<DocumentEntity> documents = documentMapper.getDocumentsByCondition(documentQueryDTO);
        int total = documentMapper.getCountByCondition(documentQueryDTO);
        Map<String, Object> map = new HashMap<>();
        map.put("list", documents);
        map.put("total",total);
        return map;
    }

    // 在原有基础上添加以下方法

    @Override
    public List<Map<String, Object>> getPendingDocuments() {
        DocumentQueryDTO queryDTO = new DocumentQueryDTO();
        queryDTO.setStatus(0); // 待审核
        queryDTO.setFileType(4); // 只查表单文件（fileType=4）
        List<DocumentEntity> formFiles = documentMapper.getPendingDocuments(queryDTO);
        if (formFiles == null) {
            formFiles = new ArrayList<>();
        }

        List<Map<String, Object>> result = new ArrayList<>();
        for (DocumentEntity formFile : formFiles) {
            if (formFile == null) continue;

            // 获取当前表单的tempId（数据库中已存在，如516c2123...）
//            String tempId = formFile.getTempId();
            String uploadName = formFile.getUploadName();
            if (uploadName == null || uploadName.isEmpty()) continue;

            // 查询同批次的所有证件（不限制fileType，只要tempId匹配）
            DocumentQueryDTO docQuery = new DocumentQueryDTO();
            docQuery.setUploadName(uploadName); // 只按tempId查询
            List<DocumentEntity> docs = documentMapper.getDocumentsByCondition(docQuery);
            if (docs == null) docs = new ArrayList<>();

            // 构建返回数据
            Map<String, Object> submission = new HashMap<>();
            submission.put("id", formFile.getId());
//            submission.put("lawyerName", "匿名提交");
            submission.put("uploadName", uploadName);
            submission.put("submitTime", formFile.getUploadTime());
            submission.put("formFileUrl", formFile.getFileName());


            // 处理证件类型（根据数据库实际fileType映射）
            Map<String, Map<String, String>> documents = new HashMap<>();
            for (DocumentEntity doc : docs) {
                if (doc == null || doc.getFileType() == 4) continue; // 跳过表单本身

                // 修正：根据数据库实际fileType值映射（1=申请表？2=身份证？3=毕业证？5=律师证？）
                String docName = switch(doc.getFileType()) {
                    case 1 -> "申请表";    // 数据库中有fileType=1的记录
                    case 2 -> "身份证";
                    case 3 -> "毕业证";
                    case 5 -> "律师执业证";
                    default -> "其他证件";
                };
                documents.put(docName, Map.of("url", doc.getFileName())); // 直接用数据库存储的fileName
            }
            submission.put("documents", documents);
            result.add(submission);
        }
        return result;
    }

    @Override
    public void updateDocumentStatus(Long id, Integer status, String remark) {


        if (id == null || status == null) {
            throw new BussinessException(ResultCode.PARAMS_ERROR);
        }
        DocumentEntity document = new DocumentEntity();
        document.setId(id);
        document.setStatus(status);
        document.setRemark(remark);
//        document.setApproveTime(new Date());
        // 实际应用中需要设置审核人ID
        // document.setApproverId(SecurityUtils.getCurrentUserId());
        int affectedRows = documentMapper.updateStatus(document);
        if (affectedRows == 0) {
            // 若影响行数为0，说明更新失败（如ID不存在）
            throw new BussinessException(ResultCode.OPERATION_FAILED);
        }
    }

    @Override
    public DocumentEntity getDocumentById(Long fileId) {
        return documentMapper.selectById(fileId);
    }

    @Override
    public DocumentEntity getDocumentByFileName(String fileName) {
        // 调用mapper层通过文件名查询
        DocumentEntity document = documentMapper.selectByFileName(fileName);
        if (document == null) {
            throw new BussinessException(ResultCode.FILE_NOT_FOUND);
        }
        return document;
    }









    @Override
    public String uploadSingleFile(Long lawyerId, MultipartFile file, Integer fileType) throws IOException {

//        String tempId = UUID.randomUUID().toString().replace("-", "");
        documentMapper.deleteByLawyerIdAndType(lawyerId, fileType);
        String originalName = file.getOriginalFilename();
        String suffix = originalName.substring((originalName.lastIndexOf(".")));
        String uuidFileNme = UUID.randomUUID().toString().replace("-", "") + suffix;
        String filePath = uploadDir + File.separator + uuidFileNme;

        //保存文件到本地
        file.transferTo(new File(filePath));

        // 记录到document表（关联律师ID）
        DocumentEntity doc = new DocumentEntity();
        doc.setLawyerId(lawyerId);
        doc.setFileName(uuidFileNme);
        doc.setFilePath(filePath);
        doc.setFileType(fileType);
        doc.setStatus(1);// 律师文件默认通过
        doc.setUploadTime(new Date());
//        doc.setUploadName(tempId);
        documentMapper.insert(doc);
        return uuidFileNme;// 返回文件名作为URL（前端通过下载接口访问）
    }


}
